package com.jqr.activity.handlerlistviewsqlitedemo.helper;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

import androidx.annotation.Nullable;

public class DatabaseHelper extends SQLiteOpenHelper {
    private  static  final String  DATABASE_NAME="school.db"; //数据库名称

    private static final  int DATABASE_VERSION=1;//版本号



    //数据表和字段
    public  static final String  TABLE_USERS="users";

    public static  final String  COLUMN_ID="id";

    public static  final String  COLUMN_NAME="name";
    public static  final String  COLUMN_AGE="age";

    public DatabaseHelper(@Nullable Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }


    private static  final String CREATE_TABLE_USERS="CREATE TABLE " + TABLE_USERS + "("
            + COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
            + COLUMN_NAME + " TEXT, "
            + COLUMN_AGE + " INTEGER)";

    @Override
    public void onCreate(SQLiteDatabase db) {
            db.execSQL(CREATE_TABLE_USERS);//创建用户表

    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        db.execSQL("DROP TABLE IF EXISTS " + TABLE_USERS); // 删除旧表
        onCreate(db);
    }
    // 插入用户数据
    public void insertUser(String name, int age) {
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put(COLUMN_NAME, name);
        values.put(COLUMN_AGE, age);
        db.insert(TABLE_USERS, null, values);
        db.close();
    }

    // 获取所有用户
    public Cursor getAllUsers() {
        SQLiteDatabase db = this.getReadableDatabase();
        return db.query(TABLE_USERS, null, null, null, null, null, null);
    }

}
